package com.itlong.cloud.operate.service.impl;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.operate.OperateBusinessChargeDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateProductModelManageGetDTO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.PO.OperationSpecialLogPO;
import com.itlong.cloud.POJO.PO.ProductModelCodeRelationPO;
import com.itlong.cloud.POJO.PO.ProductModelInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateBusinessOperationLogVO;
import com.itlong.cloud.POJO.VO.operate.OperateProductCodeGetVO;
import com.itlong.cloud.POJO.VO.operate.OperateProductModelManageGetVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.ProductModelTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.operate.dao.IOperateProductModelManageDao;
import com.itlong.cloud.operate.service.IOperateProductModelManageService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *      运营-产品型号管理服务层接口实现类
 * </desc>
 *
 * @createDate 2020/11/27
 */
@Service
public class OperateProductModelManageServiceImpl implements IOperateProductModelManageService {

    private static final Logger LOG = LoggerFactory.getLogger(OperateProductModelManageServiceImpl.class);

    @Autowired
    private IOperateProductModelManageDao iOperateProductModelManageDao;

    /**
     * <desc>
     *      获取业务日志列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2020/11/27
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateBusinessOperationLogVO> getLogPage(OperateBusinessChargeDTO operateBusinessChargeDTO) throws Exception {
        if (StringUtils.isBlank(operateBusinessChargeDTO.getOrderColumn()) || StringUtils.isBlank(operateBusinessChargeDTO.getOrderRule())) {
            operateBusinessChargeDTO.setOrderColumn("operateTime");
            operateBusinessChargeDTO.setOrderRule("DESC");
        }
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(operateBusinessChargeDTO);
        Page<OperateBusinessOperationLogVO> page = new Page<>();
        page.getPage().setPageSize(operateBusinessChargeDTO.getPageSize());
        page.getPage().setCurrentPage(operateBusinessChargeDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        params.put("outerId", operateBusinessChargeDTO.getOuterId());
        List<OperateBusinessOperationLogVO> operateBusinessOperationLogVOList = iOperateProductModelManageDao.getLogPage(params);
        page.setRows(operateBusinessOperationLogVOList, iOperateProductModelManageDao.getLogRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      分页获取任务书产品型号信息
     * </desc>
     *
     * @param operateProductModelManageGetDTO 获取任务书产品型号信息DTO
     * @return 分页任务书产品型号信息
     * @author pengwei
     * @createDate 2020/11/30
     */
    @Override
    public MessageVO getPage(OperateProductModelManageGetDTO operateProductModelManageGetDTO) throws Exception{
        if (StringUtils.isBlank(operateProductModelManageGetDTO.getOrderColumn())) {
            operateProductModelManageGetDTO.setOrderColumn("createTime");
            operateProductModelManageGetDTO.setOrderRule("DESC");
        }
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(operateProductModelManageGetDTO);
        Page<OperateProductModelManageGetVO> page = new Page<>();
        page.getPage().setPageSize(operateProductModelManageGetDTO.getPageSize());
        page.getPage().setCurrentPage(operateProductModelManageGetDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<OperateProductModelManageGetVO> operateProductModelManageVOList = iOperateProductModelManageDao.getPage(params);
        page.setRows(operateProductModelManageVOList, iOperateProductModelManageDao.getRecordCount(params));
        return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
    }

    /**
     * <desc>
     *      获取任务书产品型号详情
     * </desc>
     *
     * @param dto 获取任务书产品型号详情DTO
     * @return 任务书产品型号信息详情
     * @author pengwei
     * @createDate 2020/11/30
     */
    @Override
    public  OperateProductModelManageGetVO  getOne(OperateProductModelManageGetDTO dto) throws Exception{
        OperateProductModelManageGetVO  vo   =  iOperateProductModelManageDao.getOne(dto);
        if(vo!=null){
            List<OperateProductCodeGetVO>   relationList = iOperateProductModelManageDao.getRelatedProcCodeList(dto.getModelId());
            vo.setRelationList(relationList);
        }
        return   vo;
    }

    /**
     * <desc>
     *      任务书产品型号信息删除
     * </desc>
     *
     * @param dto 任务书产品型号dto
     * @return 任务书产品型号删除
     * @author pengwei
     * @createDate 2020/12/01
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer  delete(OperateProductModelManageGetDTO dto) throws Exception{
        //检测是否被任务书产品类型使用，若关联则不能删除
        int  relatedProdMidCnt   =  iOperateProductModelManageDao.queryRelatedProdMidCnt(dto.getModelId());
        if(relatedProdMidCnt>0){
            return  -1;
        }
        Date nowTime = new Date();
        Integer count = iOperateProductModelManageDao.delete(dto);

        // 删除任务书产品型号中间表明细数据
        iOperateProductModelManageDao.batchDeleteRelatedData(dto.getModelId());

        // 保存特殊操作日志
        OperateUserInfoPO operateUserInfoPO = iOperateProductModelManageDao.getOperateUserPO(dto.getMyUserName());
        OperationSpecialLogPO operationSpecialLogPO = new OperationSpecialLogPO();
        operationSpecialLogPO.setLogId(LogicIdUtil.bussinessId());
        operationSpecialLogPO.setOuterId(dto.getModelId());
        operationSpecialLogPO.setAccount(operateUserInfoPO.getUserName());
        operationSpecialLogPO.setRealName(operateUserInfoPO.getRealName());
        operationSpecialLogPO.setIp(dto.getIp());
        operationSpecialLogPO.setFunctionType(4);
        operationSpecialLogPO.setOperateFunction(dto.getOperateFunction());
        operationSpecialLogPO.setOperateDec(operateUserInfoPO.getRealName() + " 删除数据");
        operationSpecialLogPO.setOperateWay(dto.getOperateWay());
        operationSpecialLogPO.setStatus(DataStatusEnum.NORMAL.getType());
        operationSpecialLogPO.setCreateTime(nowTime);
        operationSpecialLogPO.setUpdateTime(nowTime);
        iOperateProductModelManageDao.save(SqlUtil.durableData(operationSpecialLogPO, PlatformConstants.TABLE_SAVE));

        return count;
    }

    /**
     * <desc>
     *      添加或者更新产品型号
     * </desc>
     *
     * @param dto 产品型号dto
     * @return
     * @author pengwei
     * @createDate 2020/12/01
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public MessageVO saveOrUpdate(OperateProductModelManageGetDTO dto) throws Exception{
        Date  nowTime  =  new Date();
        //存在相同型号
        Map<String,Object>  paramsMap  =  new HashMap<String,Object>();
        paramsMap.put("modelId",dto.getModelId());
        paramsMap.put("productModel",dto.getProductModel());
        paramsMap.put("productType", dto.getProductType());
        int  sameModelCnt = iOperateProductModelManageDao.querySameModelCnt(paramsMap);
        if(sameModelCnt>0){
            return new MessageVO(OperateErrorCodeEnum.OPERATE_PRODUCT_MODEL_MODEL_EXIST_ERR.getErrorCode());
        }
        String title  = "";
        if(StringUtils.isNotEmpty(dto.getModelId())){
            title ="修改";
            this.update(dto,nowTime);
            //批量删除中间表
            iOperateProductModelManageDao.batchDeleteRelatedData(dto.getModelId());
        }else{
            title="添加";
            dto.setModelId(LogicIdUtil.bussinessId());
            this.save(dto,nowTime);
        }
        //构造产品型号和产品编码的关系列表
        List<ProductModelCodeRelationPO>     pmcrList  = new ArrayList<>();
        String   relatedProcIds  =   dto.getRelatedProcIds();
        if(StringUtils.isNotEmpty(relatedProcIds)){
            String[]  relatedProcIdArr = relatedProcIds.split(",");
            for(int i=0;i<relatedProcIdArr.length;i++){
                ProductModelCodeRelationPO   pmcr  =  new  ProductModelCodeRelationPO();
                pmcr.setProductCode(relatedProcIdArr[i]);
                pmcr.setModelId(dto.getModelId());
                pmcr.setCreateTime(nowTime);
                pmcr.setUpdateTime(nowTime);
                pmcr.setStatus(DataStatusEnum.NORMAL.getType());
                pmcr.setCreateUserId(dto.getMyUserName());
                pmcr.setOperateUserId(dto.getMyUserName());
                pmcrList.add(pmcr);
            }
            //批量插入中间表
            iOperateProductModelManageDao.batchSaveProductModelCodeRelationData(pmcrList);
        }
        // 保存特殊操作日志
        OperateUserInfoPO operateUserInfoPO = iOperateProductModelManageDao.getOperateUserPO(dto.getMyUserName());
        OperationSpecialLogPO operationSpecialLogPO = new OperationSpecialLogPO();
        operationSpecialLogPO.setLogId(LogicIdUtil.bussinessId());
        operationSpecialLogPO.setOuterId(dto.getModelId());
        operationSpecialLogPO.setAccount(operateUserInfoPO.getUserName());
        operationSpecialLogPO.setRealName(operateUserInfoPO.getRealName());
        operationSpecialLogPO.setIp(dto.getIp());
        operationSpecialLogPO.setFunctionType(4);
        operationSpecialLogPO.setOperateFunction(dto.getOperateFunction());
        StringBuilder   descBuilder =  new StringBuilder();
        descBuilder.append(operateUserInfoPO.getRealName()).append(" ")
                .append(title).append("数据，")
                .append("产品类型为：").append(ProductModelTypeEnum.getNameByType(dto.getProductType()))
                .append(",产品名称为：").append(dto.getProductName())
                .append(",产品型号为：").append(dto.getProductModel())
                .append(",型号图片地址为：").append(dto.getDeviceImageStr());
        operationSpecialLogPO.setOperateDec(descBuilder.toString());
        operationSpecialLogPO.setOperateData(JSON.toJSONString(dto));
        operationSpecialLogPO.setOperateWay(dto.getOperateWay());
        operationSpecialLogPO.setStatus(DataStatusEnum.NORMAL.getType());
        operationSpecialLogPO.setCreateTime(nowTime);
        operationSpecialLogPO.setUpdateTime(nowTime);
        iOperateProductModelManageDao.save(SqlUtil.durableData(operationSpecialLogPO, PlatformConstants.TABLE_SAVE));
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
    }

    /**
     * <desc>
     *      更新
     * </desc>
     *
     * @param dto 产品型号dto
     * @param nowTime 时间nowTime
     * @return
     * @author pengwei
     * @createDate 2020/12/01
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    protected Integer update(OperateProductModelManageGetDTO dto,Date  nowTime ) throws  Exception{
        // 构造产品型号信息数据
        OperateProductModelManageGetVO  vo  = iOperateProductModelManageDao.getOne(dto);
        ProductModelInfoPO   pmi   = new ProductModelInfoPO();
        pmi.setProductModel(StringUtils.isNotEmpty(dto.getProductModel())?dto.getProductModel():vo.getProductModel());
        pmi.setProductType(StringUtils.isNotEmpty(dto.getProductType())?dto.getProductType():vo.getProductType());
        pmi.setProductName(StringUtils.isNotEmpty(dto.getProductName())?dto.getProductName():vo.getProductName());
        pmi.setDeviceImageUrl(dto.getDeviceImageStr());
        pmi.setModelId(dto.getModelId());
        pmi.setUpdateTime(nowTime);
        pmi.setOperateUserId(dto.getMyUserName());
        pmi.setStatus(DataStatusEnum.NORMAL.getType());
        Integer   count  =  iOperateProductModelManageDao.update(SqlUtil.durableData(pmi, PlatformConstants.TABLE_UPDATE));
        return   count;
    }

    /**
     * <desc>
     *      新增
     * </desc>
     *
     * @param dto 产品型号dto
     * @param nowTime 时间nowTime
     * @return
     * @author pengwei
     * @createDate 2020/12/01
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    protected  Integer  save(OperateProductModelManageGetDTO  dto,Date  nowTime ) throws  Exception{
        // 构造产品型号信息数据
        ProductModelInfoPO   pmi   = new ProductModelInfoPO();
        pmi.setProductModel(dto.getProductModel());
        pmi.setProductName(dto.getProductName());
        pmi.setProductType(dto.getProductType());
        pmi.setDeviceImageUrl(dto.getDeviceImageStr());
        pmi.setModelId(dto.getModelId());
        pmi.setCreateTime(nowTime);
        pmi.setUpdateTime(nowTime);
        pmi.setCreateUserId(dto.getMyUserName());
        pmi.setOperateUserId(dto.getMyUserName());
        pmi.setStatus(DataStatusEnum.NORMAL.getType());
        Integer  count = iOperateProductModelManageDao.save(SqlUtil.durableData(pmi, PlatformConstants.TABLE_SAVE));
        return   count;
    }

    /**
     * <desc>
     *      获取产品型号相关产品编码列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author pengwei
     * @createDate 2020/12/02
     */
    public   Page<OperateProductCodeGetVO> getRelatedProcCodePage(OperateProductModelManageGetDTO dto) throws Exception{
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(dto);
        Page<OperateProductCodeGetVO> page = new Page<>();
        page.getPage().setPageSize(dto.getPageSize());
        page.getPage().setCurrentPage(dto.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<OperateProductCodeGetVO> vOList = iOperateProductModelManageDao.getRelatedProcCodePage(params);
        page.setRows(vOList, iOperateProductModelManageDao.getRelatedProcCodeRecordCount(params));
        return page;
    }


    /**
     * <desc>
     *      获取产品型号相关产品编码列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author pengwei
     * @createDate 2020/12/02
     */
    public  Page<OperateProductCodeGetVO> getProcCodePage(OperateProductModelManageGetDTO dto) throws Exception{
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(dto);
        Page<OperateProductCodeGetVO> page = new Page<>();
        page.getPage().setPageSize(dto.getPageSize());
        page.getPage().setCurrentPage(dto.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<OperateProductCodeGetVO> vOList = iOperateProductModelManageDao.getProcCodePage(params);
        page.setRows(vOList, iOperateProductModelManageDao.getProcCodeRecordCount(params));
        return page;
    }
}
